package com.nbsaas.boot;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class MyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 客户端连接时执行的操作
        System.out.println("Client connected: " + ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 接收到客户端的WebSocket消息时执行的操作
        String message = msg.text();
        System.out.println("Received message: " + message);

        // 可以在这里处理消息，然后向客户端发送响应
        ctx.writeAndFlush(new TextWebSocketFrame("Server Response: " + message));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 客户端断开连接时执行的操作
        System.out.println("Client disconnected: " + ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 发生异常时执行的操作
        cause.printStackTrace();
        ctx.close();
    }
}
